/**
 * This file is released under the GNU General Public License.
 * Refer to the COPYING file distributed with this package.
 *
 * Copyright (c) 2008-2009 WURFL-Pro srl
 */
package net.sourceforge.wurfl.core.handlers.matchers;

import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;

import net.sourceforge.wurfl.core.handlers.Handler;
import net.sourceforge.wurfl.core.utils.StringUtils;

/**
 * @author WURFL-PRO SRL, Rome, Italy
 * @version $Id: CatchAllMatcher.java 1045 2009-03-09 15:52:53Z filippo.deluca $
 */
public class CatchAllMatcher extends AbstractMatcher {

	public CatchAllMatcher(Handler handler) {
		super(handler);
	}

	protected String lookForMatchingUserAgent(SortedSet userAgentsSet, String userAgent) {
		if (userAgent.startsWith("Mozilla")) {
			if (userAgent.startsWith("Mozilla/4")) {
				return StringUtils
						.ldMatch(getMozillaData(userAgentsSet, "Mozilla/4"), userAgent, MOZILLA_LD_TOLLERANCE);
			}

			if (userAgent.startsWith("Mozilla/5")) {
				return StringUtils
						.ldMatch(getMozillaData(userAgentsSet, "Mozilla/5"), userAgent, MOZILLA_LD_TOLLERANCE);
			}

			return StringUtils.ldMatch(getMozillaData(userAgentsSet, "Mozilla"), userAgent, MOZILLA_LD_TOLLERANCE);
		}
		
		return super.lookForMatchingUserAgent(userAgentsSet, userAgent);
	}

	private SortedSet getMozillaData(SortedSet userAgentsSet, String starting) {

		SortedSet set = new TreeSet();
		for (Iterator iterator = userAgentsSet.iterator(); iterator.hasNext();) {
			String userAgent = (String) iterator.next();
			if (userAgent != null && userAgent.startsWith(starting)) {
				set.add(userAgent);
			}
		}
		return set;
	}

	private static final int MOZILLA_LD_TOLLERANCE = 4;
}
